package com.geline.luckysheet.datasource;

import cn.hutool.core.util.StrUtil;
import com.geline.easytrans.dict.DictOptions;
import com.geline.easytrans.enums.DataTypeEnum;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 条件表达式
 * @author: mengxin
 * @date: 2022/10/13 14:36
 */
@Slf4j
@Getter
public enum ExprEnum {
    eq("=", "%s = %s"),
    gt(">", "%s > %s"),
    gte(">=", "%s >= %s"),
    lt("<", "%s < %s"),
    lte("<=", "%s <= %s"),
    ne("!=", "%s != %s"),
    like("like", "%s like %s "),
    in("in", "%s in (%s) "),
    notIn("not in", "%s not in (%s) ");

    private String label;
    private String expr;

    ExprEnum(String label, String expr){
        this.label = label;
        this.expr = expr;
    }

    //查询字典列表
    public static List<DictOptions> toList(){
        return Stream.of(ExprEnum.values()).map(row ->{
            DictOptions options = new DictOptions();
            options.setDictLabel(row.getLabel());
            options.setDictValue(row.name());
            return options;
        }).collect(Collectors.toList());
    }

    /**
     * 构造一条where语句
     * @param variable
     * @return
     */
    public static String createSql(ReqParam variable, String value) {
        String column = variable.getColumnName().trim();
        DataTypeEnum dataType = variable.getColumnType();
        ExprEnum expr = ExprEnum.valueOf(variable.getExpr());
        if(in==expr || notIn==expr){
            List<String> valueList = Arrays.asList(value.split(","));
            if(valueList!=null && valueList.size()>0){
                String valueStr = "";
                if(dataType== DataTypeEnum.String){
                    valueStr = "'"+StrUtil.join("','", valueList)+"'";
                }else {
                    valueStr = StrUtil.join(",", valueList);
                }
                return String.format(expr.getExpr(), column, valueStr);
            }else {
                log.warn("can not find valueList !");
            }
        }else if(like==expr){
            String valueStr = value.indexOf("%")>=0 ? "'"+value+"'" : "'%"+value+"%'";
            return String.format(expr.getExpr(), column, valueStr);
        }else {
            String valueStr = dataType==DataTypeEnum.String ? "'"+value+"'" : value;
            return String.format(expr.getExpr(), column, valueStr);
        }
        return null;
    }
}
